import axios from "axios";

/**
 * 获取github release真实下载地址
 * @param projectUrl github 相关项目的地址
 * @returns downUrl 真实下载地址
 */
export const getGitReleaseDownUrl = async (projectUrl, searchName) => {
  const [a, b, c, userName, projectName] = projectUrl.split("/");
  const releaseInfoUrl = `https://api.github.com/repos/${userName}/${projectName}/releases/latest`;
  const releaseInfo = await axios.get(releaseInfoUrl);
  const { assets, tag_name } = releaseInfo.data;
  let downUrl = "";
  for (const item of assets) {
    // 如果有搜索条件，按照搜索条件来。否则按照版本匹配到的第一个资源来
    if (searchName) {
      if (item.name.indexOf(searchName) > 1) {
        downUrl = item.browser_download_url;
      }
    } else {
      if (item.name.indexOf(tag_name)) {
        // 获取最新的资源
        downUrl = item.browser_download_url;
        break;
      }
    }
  }
  return {
    url: downUrl,
  };
};
